(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.lookup.siteMoreDataController', siteMoreDataController);
	siteMoreDataController.$inject = [ '$scope', '$q', '$uibModalInstance', 'Constants', 'dialogsModule', 'gridService', 'modalService', 'layoutConfig', 'validatorConfig', 'authService' ];
	function siteMoreDataController($scope, $q, $uibModalInstance, Constants, dialogsModule, gridService, modalService, layoutConfig, validatorConfig, authService) {
		var ctrl = this, log = $scope.loggerFactory.getLogger("siteMoreDataLookup");
		ctrl.dialogsModule = dialogsModule;
		ctrl.config = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		
		ctrl.ok = function() {
			if (!dialogsModule.btnCallback || !dialogsModule.btnCallback['ok'] || dialogsModule.btnCallback['ok'](ctrl.site.map) !== false) {
				$uibModalInstance.close();
			}
		};
		
		ctrl.close = function() {
			if (!dialogsModule.btnCallback || !dialogsModule.btnCallback['close'] || dialogsModule.btnCallback['close']() !== false) {
				$uibModalInstance.dismiss();
			}
		};
		
		ctrl.init = function() {
			ctrl.gridOptions = gridService.createInnerGridOptions($scope, ctrl.config.tableConfigs.table1, rowSelectionChanged);
			ctrl.gridOptions.data = 'vm.site.map';
			ctrl.site = {};
			ctrl.search();
		};
		
		ctrl.addSiteMoreData = function(){
			var temp = ctrl.site.map;
			angular.forEach(ctrl.selectedRows, function(selectedParam, key) {
				angular.forEach(temp, function(param, index) {
					if (param.key == selectedParam.key) {
						ctrl.site.map.splice(index, 1);
						pushArray(ctrl.site.map, param);
					}
				});
			});
		};
		function rowSelectionChanged(eventRow, selectedRows) {
			ctrl.selectedRows = selectedRows;
		}
		ctrl.removeSiteMoreData = function(){
			var temp = ctrl.site.map;
			angular.forEach(ctrl.map, function(map, key) {
				angular.forEach(temp, function(param, index) {
					if (param.key == selectedParam.key) {
						ctrl.site.map.splice(index, 1);
						pushArray(ctrl.site.map, param);
					}
				});
			});
		};
		
		function pushArray(array1, value){
			if(array1.length == 0){
				array1.push(value);
				return;
			}else if(array1[array1.length - 1].parmDispOrder < value.parmDispOrder){
				array1.push(value);
				return;
			}
			var temp = array1;
			var returnFlag = true;
			angular.forEach(temp, function(array, key){
				if(returnFlag){
					if(array.parmDispOrder > value.parmDispOrder){
						array1.splice(key, 0, value);
						returnFlag = false;
					}
				}
			});
		}

		ctrl.search = function() {
			if(ctrl.dialogsModule.params && ctrl.dialogsModule.params.moreData){
				ctrl.site.moreData = ctrl.dialogsModule.params.moreData;
			}
			authService.search(ctrl.site).then(function(response) {
				angular.merge(ctrl.site, response.data);
				gridService.updateGridOptions(ctrl.site, ctrl.availableProperties);
			}, angular.noop);
		};


	}
})(angular);
